package zhoufu.sz.sanxiao_check.utils;

/**
 * 项目 : ShanMoDaYe_Android
 * 作者 : HYC
 * 时间 : 2015/11/2 16:24
 * 功能 : todo
 */

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import zhoufu.sz.sanxiao_check.App;
import zhoufu.sz.sanxiao_check.ui.check.PreHtmlViewActivity;

/**
 */
public class UIUtils
{
    private static int screenWidth  = 0;
    private static int screenHeight = 0;


    /**
     * 上下文的获取
     */
    public static Context getContext()
    {
        return App.getApp();
    }

    /**
     * 获取资源
     */
    public static Resources getResources()
    {
        return getContext().getResources();
    }


    /**
     * @param dip
     * @return
     */
    public static int dip2px(int dip)
    {
        // 公式 1: px = dp * (dpi / 160)
        // 公式 2: dp = px / denistity;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float          density = metrics.density;
        // metrics.densityDpi
        return (int) ( dip * density + 0.5f );
    }

    public static int px2dip(int px)
    {
        // 公式 1: px = dp * (dpi / 160)
        // 公式 2: dp = px / denistity;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float          density = metrics.density;
        // metrics.densityDpi
        return (int) ( px / density + 0.5f );
    }

    public static String getString(int resId)
    {
        return getResources().getString(resId);
    }

    public static String getString(int resId, Object... formatArgs)
    {
        return getResources().getString(resId, formatArgs);
    }

    public static String getPackageName()
    {
        return getContext().getPackageName();
    }

    public static String[] getStringArray(int resId)
    {
        return getResources().getStringArray(resId);
    }

    public static int getColor(int resId)
    {
        return getResources().getColor(resId);
    }

    public static int getScreentWidth(Activity context)
    {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;// 获取屏幕分辨率宽度
    }


    //获取屏幕高度
    public static int getScreenHeight(Context c)
    {
        if ( screenHeight == 0 )
        {
            WindowManager wm      = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
            Display       display = wm.getDefaultDisplay();
            Point         size    = new Point();
            display.getSize(size);
            screenHeight = size.y;
        }

        return screenHeight;
    }

    //获取屏幕宽度
    public static int getScreenWidth(Context c)
    {
        if ( screenWidth == 0 )
        {
            WindowManager wm      = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
            Display       display = wm.getDefaultDisplay();
            Point         size    = new Point();
            display.getSize(size);
            screenWidth = size.x;
        }

        return screenWidth;
    }

    public static void showSnackbar(View view, int stringId)
    {
        Snackbar.make(view, getString(stringId), Snackbar.LENGTH_SHORT).show();
    }

    public static void showSnackbar(View view, String msg)
    {
        Snackbar.make(view, msg, Snackbar.LENGTH_SHORT).show();
    }

    //检验版本
    public static boolean isAndroid5()
    {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }

    /**
     * 显示Dialog是否可以取消
     */
    public static AlertDialog showDialog(String title, String message,
            DialogInterface.OnClickListener onOKClickListener, boolean isCancelAble,
            Context context)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        AlertDialog alertDialog = builder.setTitle(title)
                .setMessage(message)
                .setPositiveButton("确定",
                        onOKClickListener)
                .setCancelable(isCancelAble)
                .create();
        alertDialog.show();
        return alertDialog;
    }

    private static Toast toast;

    public static void showToast(Context context,
            String content)
    {
        if ( toast == null )
        {
            toast = Toast.makeText(context,
                    content,
                    Toast.LENGTH_SHORT);
        } else
        {
            toast.setText(content);
        }
        toast.show();
    }

    public static void setDialogWindowAttr(Dialog dlg, Context context)
    {
        Window                     window = dlg.getWindow();
        WindowManager.LayoutParams lp     = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = getScreenWidth(context) - UIUtils.dip2px(40);//宽高可设置具体大小
        dlg.getWindow().setAttributes(lp);
    }

    /**
     * 安装apk
     */
    public static boolean install(Context context)
    {
        PackageInfo packageInfo;
        try
        {
            packageInfo = context.getPackageManager().getPackageInfo(
                    PreHtmlViewActivity.mPrintPackageName, PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e)
        {
            packageInfo = null;
            e.printStackTrace();
        }
        if ( packageInfo == null )
        {
            System.out.println("没有安装");
            String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/print.apk";
            copyApkFromAssets(context, "print.apk", path);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + path),
                    "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return false;
        } else
        {
            System.out.println("已经安装");
            return true;
        }
    }

    public static boolean copyApkFromAssets(Context context, String fileName, String path)
    {
        boolean copyIsFinish = false;
        try
        {
            InputStream is   = context.getAssets().open(fileName);
            File        file = new File(path);
            file.createNewFile();
            FileOutputStream fos  = new FileOutputStream(file);
            byte[]           temp = new byte[1024];
            int              i    = 0;
            while (( i = is.read(temp) ) > 0)
            {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            copyIsFinish = true;
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return copyIsFinish;
    }

    public static void savebadge(Context context)
    {
        File badgeFile = new File(context.getExternalCacheDir(), "badge.png");
        Log.e("ss", badgeFile.getPath());
        InputStream      inputStream;
        FileOutputStream outputStream;
        try
        {
            inputStream = context.getAssets().open("badge.png");
            outputStream = new FileOutputStream(badgeFile);
            FileUtils.copy(inputStream, outputStream);
            if ( inputStream != null )
            {
                inputStream.close();
            }
            if ( outputStream != null )
            {
                outputStream.close();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
